﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf.Message;

namespace UI
{
    //activity_sign_tab	每日签到
    //super_everyday_sign 豪华签到
    //mouth_everyday_sign_count 本月已经签到：{0}/{30}
    //everyday_sign_tip 每日签到一次，既可领取相应的奖励


    /// <summary>
    /// 签到
    /// </summary>
    public class UIActivityEveryDaySign : UIActivityTemplate
    {
        #region tab
        public GameObject normalSign;
        public GameObject normalSignTab;
        public GameObject superSign;
        public GameObject superSignTab;
        public int currentTab = 0;
        #endregion

        #region 普通签到
        public GameObject iconTemplate;
        public UIGrid norGrid;
        public List<MonthRewardItem> datas;
        public int currentDay;
        public UILabel signCount;
        #endregion

        #region 豪华签到
        public string superNeed;
        public string superItems;
        public int superState;
        public UIButton btn;

        public GameObject superIcon;
        public UIGrid superGrid;
        public UILabel needRecharge;
        public GameObject state0, state1, state2;
        #endregion


        #region sign tip
        public GameObject normalTip;
        public GameObject superTip;
        #endregion

        public override void Init(UIActivity activity)
        {
            base.Init(activity);
            currentTab = 0;
        }

        void Start()
        {
            DataMessageTool.AddHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);//红点消息处
            ShowOrHideRedPoint(new object());
        }

        private void PrepareDataFormNet()
        {
            NetAPI.SendHttp(OpDefine.CSRewardMonthSignList, new CSRewardMonthSignList(), (obj, ok) => 
            {
                if(ok)
                {
                    var signLs = obj.kBody as SCRewardMonthSignList;
                    datas = new List<MonthRewardItem>();
                    currentDay = signLs.currentDay;
                    superNeed = signLs.luxuryNeedPay;
                    superItems = signLs.luxuryReward;
                    superState = signLs.luxuryState;
                    
                    datas.AddRange(signLs.list);
                    RebuildAllIcons();
                }
            });
        }

        protected override void PrepareData()
        {
            activityType = ActivityType.EveryDaySign;
        }

        public override void Show()
        {
            PrepareDataFormNet();
            base.Show();            
        }

        void ShowOrHideRedPoint(object o)
        {
            //Debug.Log("Every data refresh red point");
            if (normalTip == null)
                return;
            normalTip.SetActive(StaticData.redTips.GetStateByType(RedPointTip.Red.dailySignOrdinary));
            superTip.SetActive(StaticData.redTips.GetStateByType(RedPointTip.Red.dailySignLuxury));

        }

        protected override void RebuildAllIcons()
        {
            Clear();
            datas.Sort((lh, rh) => { return lh.day - rh.day; });

            activity.StopCoroutine("_RebuildAllIcons");
            activity.StartCoroutine(_RebuildAllIcons());
        }

        

        IEnumerator _RebuildAllIcons()
        {
            int total = 0;
            int curr = 0;
            int i = 0;
            foreach (var it in datas)
            {
                var icon = GetIcon(name + ":" + it.rewardId + ":" + it.day + it.getState, iconTemplate);
                icon.SetActive(false);
                icon.transform.SetParent(norGrid.transform);
                icon.transform.localScale = Vector3.one;
                icon.SetActive(true);
                icon.GetComponent<UIActivitySignIcon>().Init(it,currentDay,this);
               

                if (++i % 15 == 0)
                {
                    norGrid.Reposition();
                    yield return null;
                }
                total++;
                if(it.day<currentDay)
                {
                    curr++;
                }
                else if(it.day == currentDay )
                {
                    if(it.getState==2 || it.getState==3)
                    {
                        curr++;
                    }
                }
            }
            signCount.text = curr + "/" + total;
            norGrid.Reposition();
            ShowTab(currentTab);
            yield return null;
            //coin,10000;item_001,1

            if (superItems.Contains(";"))
            {
                var itemWithNums = superItems.Split(new char[1] { ';' }, System.StringSplitOptions.RemoveEmptyEntries);
                foreach (var it in itemWithNums)
                {
                    var items = it.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                    var id = items[0];
                    var num = items[1];

                    var inst = GetIcon(name + ":" + id + "@" + num+":", superIcon);
                    inst.transform.SetParent(superGrid.transform);
                    inst.transform.localScale = Vector3.one;
                    inst.SetActive(true);

                    var script = inst.GetComponent<CommonIcon>();
                    script.SetData(id, true, int.Parse(num));
                }
            }
            else
            {
                var items = superItems.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                var id = items[0];
                var num = items[1];

                var inst = GetIcon(name + ":" + id + "@" + num + ":", superIcon);
                inst.transform.SetParent(superGrid.transform);
                inst.transform.localScale = Vector3.one;
                inst.SetActive(true);
                

                var script = inst.GetComponent<CommonIcon>();
                script.SetData(id, true, int.Parse(num));
            }
            superGrid.Reposition();

            needRecharge.text = superNeed;
            SetSuperButtonState();
        }
        

        void SetSuperButtonState()
        {
            state0.SetActive(false);
            state1.SetActive(false);
            state2.SetActive(false);
            btn.enabled = true;
            if (superState == 0)
            {
                state0.SetActive(true);
            }
            else if (superState == 1)
            {
                state1.SetActive(true);
            }
            else if (superState == 2)
            {
                state2.SetActive(true);
                btn.enabled = false;
            }
        }

        void ShowTab(int i)
        {
            if (i == 0)
            {
                normalSign.SetActive(true);
                normalSignTab.SetActive(true);
                superSign.SetActive(false);
                superSignTab.SetActive(false);
                currentTab = 0;
            }
            else
            {
                normalSign.SetActive(false);
                normalSignTab.SetActive(false);
                superSign.SetActive(true);
                superSignTab.SetActive(true);
                currentTab = 1;
            }
        }

        public void OnClickNormalSign()
        {
            ShowTab(0);
        } 

        public void OnClickSuperSign()
        {
            ShowTab(1);
        }

        public override void OnCoverPageRemove()
        {
            if (activity.panel.activedType == activityType)
                PrepareDataFormNet();
        }

        public void OnClickSuper()
        {
            if (superState == 0)
            {
                UI.PageManager.Instance.OpenPage("ChargePage", "");
            }
            else if (superState == 1)
            {
                NetAPI.SendHttp(OpDefine.CSReceiveLuxurySign, new CSReceiveLuxurySign(), (o, ok) => 
                {
                    if(ok)
                    {
                        var recv = (SCReceiveLuxurySign)o.kBody;
                        StaticData.playerData.AddResultObj(recv.get);
                        BoxManager.CreatePopupTextBox(TableTextBlo.GetText("sign_success_get_reward_item"));
                        superState = 2;//表示已经领取了

                        SetSuperButtonState();
                        StaticData.redTips.SetPointState(RedPointTip.Red.dailySignLuxury, 0); 
                    }
                });
            }
            else if (superState == 2)
            {
            }
        }

        public override void Hide()
        {
            base.Hide();
        }

        void OnDestroy()
        {
            DataMessageTool.RemoveHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);
        }
    }
    
}